package com.springboot.controller;

import com.springboot.common.base.ResponseResult;
import com.springboot.common.constant.ErrorCode;
import com.springboot.common.exception.BusinessException;
import com.springboot.entity.UserEntity;
import com.springboot.repository.UserRepository;
import com.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    private UserRepository userRepository;


    @PostMapping("/save")
    public UserEntity save(UserEntity entity) {
        UserEntity save = null;
        try {
            save = userService.save(entity);
        } catch (Exception e) {
//            e.printStackTrace();
            throw new BusinessException(ErrorCode.ERROR, "保存用户信息错误。");
        }
        return save;
    }

    @GetMapping("/list")
    public ResponseResult<List<UserEntity>> list() {
        return new ResponseResult<List<UserEntity>>(userRepository.findAll());
    }

    static class User {
        public String id;
    }

    public static void main(String[] args) throws InterruptedException {
        UserController userController = new UserController();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                userController.write();
            }
        });
        t1.start();
        t1.sleep(1000L);

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                userController.read();
            }
        });

        t2.start();

    }

    int a = 0;
    boolean flag = false;

    public void write(){
        a = 1;
        flag = true;
    }

    public void read(){
        if(flag){
            int i  = a * a;
            System.out.println("i = "+i);
        }
    }



}
